const bmpConvert = require('./jl_bmpconvert_2.0.0-beta1.js');
// import { MessageConstant } from "../base/workTask";
const workTask = require('../base/workTask.js');

class BmpConvertMessage {
    /**
     * 消息-bitmap图像转换
    */
    static MSG_BITMAP_CONVERT = "message_bitmap_convert"
}
class Result {
    // 大于0，意味着转码成功
    static RESULT_SUCCESS = 1;
    // 小于等于0, 视为转码失败，负数为错误码
    static RESULT_ERROR = -0xE00;
    static RESULT_ERROR_INVALID_PARAM = -0xE01;
    static RESULT_ERROR_IO_EXCEPTION = -0xE02;
}
class Key {
    static FUNC = "func"

    /*****************************************输入参数*********************************/

    /**
     * 输入数据(bitmap-像素-BGRA格式)
    */
    static IN_BUFFER = "in_buffer"
    /**
     * 转码算法
    */
    static FLAG = "flag"
    /**
     * 图像宽度
    */
    static WIDTH = "width"
    /**
     * 图像高度
    */
    static HEIGHT = "height"

    /**
     * 编码格式
    */
    static FORMAT = "format"


    /*****************************************输出结果参数*********************************/

    /**
    * 结果码
    * <p>
    * 说明:<br/>
    * 1. 小于等于0, 视为转码失败，负数为错误码<br/>
    * 2. 大于0，意味着转码成功
    * </p>
    */
    static RESULT = "result"
    /**
     * 算法类型
     */
    static ALGORITHM = "algorithm"
    /**
     * 输出数据大小
     */
    static OUTPUT_BUFFER_SIZE = "output_buffer_size"
    /**
     * 输出数据
     */
    static OUTPUT_BUFFER = "output_buffer"
    /**
     * 图像格式
     *  <p>
     * 说明: 从707N算法后，增加该字段，用于【不打包算法】的处理
     * </p>
     */
    static PIXEL_FORMAT = "pixel_format"
    /**
     * 压缩模式
     * <p>
     * 说明: 从707N算法后，增加该字段，用于【不打包算法】的处理
     * </p>
     */
    static COMPRESS_MODE = "compress_mode"
}

var moduleIsInit = false;
function onError(errorCode) {
    const messageObj = new Object();
    messageObj[Key.FUNC] = workTask.MessageConstant.MSG_FINISHED;
    messageObj[Key.RESULT] = errorCode;
    worker.postMessage(messageObj);
}
function onStart() {
    const messageObj = new Object();
    messageObj[Key.FUNC] = workTask.MessageConstant.MSG_START;
    worker.postMessage(messageObj);
}
const inputFileName = "input_file.bin"
const outputFileName = "output_file.bin"
// setTimeout(() => {
//     console.log( " bmpConvert module ",bmpConvert.Module);
//   }, 2000);
worker.onMessage(function (msg) {
    if (!moduleIsInit) {
        moduleIsInit = bmpConvert.Module.calledRun;        
    }
    // processing of workder
    console.log("worker.onMessage bitmap convert", msg);
    const func = msg[Key.FUNC];

    if (msg[Key.FUNC] === workTask.MessageConstant.MSG_TERMINATE) {
        //结束当前worker
        console.log("当前worker 中止结束");
        onError(Result.RESULT_ERROR)
    } else if (func === BmpConvertMessage.MSG_BITMAP_CONVERT
    ) {
        //bitmap图像转换
        console.log("worker.onMessage bitmap图像转换", msg);
        const Module = bmpConvert.Module;
        const inBuffer = msg[Key.IN_BUFFER];
        const flag = msg[Key.FLAG];
        const width = msg[Key.WIDTH];
        const height = msg[Key.HEIGHT];
        const format = msg[Key.FORMAT]
        if (inBuffer === undefined) {
            console.log(" inBuffer is undefined");
            onError(Result.RESULT_ERROR_INVALID_PARAM)
            return;
        }

        const tempInBuffer = new Uint8Array(inBuffer);
        // console.log("worker.onMessage bitmap图像转换", tempInBuffer);
        // console.log("worker.onMessage bitmap图像转换", tempInBuffer.length);
        //
        let runFunction = function () { }
        const initFunction = function () {
            const inputPtr = Module._malloc(Module.lengthBytesUTF8(inputFileName) + 1)
            Module.stringToUTF8(inputFileName, inputPtr, Module.lengthBytesUTF8(inputFileName) + 1);

            const outputPtr = Module._malloc(Module.lengthBytesUTF8(outputFileName) + 1)
            Module.stringToUTF8(outputFileName, outputPtr, Module.lengthBytesUTF8(outputFileName) + 1);
            return { inputPtr: inputPtr, outputPtr: outputPtr }
        }
        const resultFunction = function (result) {
            let outputData = undefined
            if (result.result >= Result.RESULT_SUCCESS) {
                outputData = Module.FS.readFile(outputFileName, { encoding: 'binary' });
                console.log('Binary Data (first 16 bytes):', outputData.slice(0, 16));
            }
            console.log('Conversion Result:', result);
            console.log('Output Data:', outputData);
            // 通知 任务已结束了
            const messageObj = new Object();
            messageObj[Key.FUNC] = workTask.MessageConstant.MSG_FINISHED;
            messageObj[Key.RESULT] = result.result;
            messageObj[Key.OUTPUT_BUFFER] = outputData?.buffer;
            messageObj[Key.PIXEL_FORMAT] = result.pixel_format;
            messageObj[Key.COMPRESS_MODE] = result.compress_mode;

            worker.postMessage(messageObj);
        }
        if (func === BmpConvertMessage.MSG_BITMAP_CONVERT) {
            console.log("worker.onMessage Bmp转换Bin", msg);
            runFunction = function () {
                onStart();
                const ptrObj = initFunction()
                // 使用 Module.cwrap 导出函数

                const emscripten_bmp_convert = Module.cwrap('bmp_convert', 'number', [
                    'number', 'string', 'number', 'number', 'string', 'number', 'number'
                ]);
                const resultSize = 16; 
                const resultPtr = Module._malloc(resultSize);
                // 调用 C 函数
                try {
                    const ret = emscripten_bmp_convert(flag, inputFileName, width, height, outputFileName, format, resultPtr);
                    if (ret === 0) {
                        // 读取字段
                        const result = Module.HEAP32[resultPtr >> 2];
                        const algorithm = Module.HEAP32[(resultPtr + 4) >> 2];
                        const buf_size = Module.HEAP32[(resultPtr + 8) >> 2];
                        const pixel_format = Module.HEAP32[(resultPtr + 12) >> 2];
                        const compress_mode = Module.HEAP32[(resultPtr + 16) >> 2];
                        console.log('result:', result);
                        console.log('algorithm:', algorithm);
                        console.log('buf_size:', buf_size);
                        console.log('pixel_format:', pixel_format);
                        console.log('compress_mode:', compress_mode);
                        Module._free(resultPtr);

                        // 释放内存（注意：C 函数中必须 free 或手动管理）
                        resultFunction({
                            result: result,
                            algorithm: algorithm,
                            buf_size: buf_size,
                            pixel_format: pixel_format,
                            compress_mode: compress_mode
                        }, ptrObj)
                    } else {
                        Module._free(resultPtr);

                        resultFunction({
                            result: Result.ERR_ERROR
                        })
                    }

                } catch (error) {
                    console.warn("emscriptenBmpConvert has error", error)
                    resultFunction({
                        result: Result.ERR_ERROR
                    })
                }
            }
        }

        Module.onRuntimeInitialized = function () {
            // 初始化完成
            console.log("module.onRuntimeInitialized", Module);
            Module.FS.createDataFile('/', inputFileName, tempInBuffer, true, true);
            moduleIsInit = true;
            runFunction()
        }

        if (moduleIsInit) {
            Module.FS.createDataFile('/', inputFileName, tempInBuffer, true, true);
            runFunction()
        }
    }
})
